package jtm.project.exercise;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * This class contains the actions with user's table 
 * @author Javier Tejedor
 */
public class RoleDAO implements RoleDAOInterface {

	private static RoleDAO roleDAO;

	/**
	 * this returns an instance of UserDAO. (Singleton Pattern)
	 * @return
	 */
	public static RoleDAO getRoleDAO() {
		if(roleDAO == null){
			roleDAO = new RoleDAO();
		}
		return roleDAO;
	}
	
	/**
	 * returns an object with a specific id
	 */
	public Role selectById(int id) {
		Session session = getSession();
		
		Role role = (Role) session.get(Role.class, id);
	    
	    closeSession();
	    return role;
	}


	/**
	 * returns all elements of the table
	 */
	public List<Role> selectAll() {
	    Session session = getSession();
	    
		List<Role> roles = (List<Role>) session.createQuery("from Role").list();
		
		closeSession();
	    return roles;
	}
	
	/**
	 * returns the elements with the name passed by parameters
	 * @param name
	 * @return
	 */
	public List<Role> selectAllByName(String name) {
		Session session = getSession();
		
		List<Role> roles = null;
		
		Query whereClause = 
				session.createQuery("from Role where name = '" + name + "'");
		
		try {
			roles = whereClause.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		closeSession();
		return roles;
	}

	/**
	 * this inserts one row into the table
	 */
	public int insert(Role role) {
		Session session = getSession();
		
	    session.beginTransaction();
	 
	    Integer id = (Integer) session.save(role);
	    role.setId(id);
	         
	    session.getTransaction().commit();
	    
	    closeSession();
	    
	    return id;
	}


	/**
	 * this updates one row into the table
	 */
	public void update(Role role) {
		Session session = getSession();
		
	    session.beginTransaction();
	    session.merge(role);
	    session.getTransaction().commit();
	    
	    closeSession();
	}

	/**
	 * this deletes one row from the table
	 */
	public void delete(Role role) {
		Session session = getSession();
		
	    session.beginTransaction();
	    session.delete(role);
	    session.getTransaction().commit();
	    
	    closeSession();
	}

	/**
	 * This method saves or updates, depending if the object exist or not
	 * @param role
	 */
	public void saveOrUpdate(Role role) {
		Session session = getSession();
		
	    session.beginTransaction();
	    
	    session.saveOrUpdate(role);
	    session.getTransaction().commit();
	    
	    closeSession();
	}

	/**
	 * this returns the session
	 * @return
	 */
	private Session getSession(){
		return HibernateSession.getSession();
	}
	
	/**
	 * this close the session
	 */
	private void closeSession(){
		HibernateSession.closeSession();
	}

}
